package ebedynky.validators;

import ebedynky.beans.DeliveryPlace;
import ebedynky.services.DeliveryPlaceService;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 * @author Ondrej David (davidon1)
 */
public class DeliveryPlaceValidator implements Validator {

    /**
     * Checks whether class for validation is DeliveryPlace class.
     * @param clazz to be validated
     * @return is/isn't Product class
     */
    @Override
    public boolean supports(Class clazz) {
        return (DeliveryPlace.class.equals(clazz));
    }

    @Override
    public void validate(Object obj, Errors err) {
        if (obj instanceof DeliveryPlace) {
            DeliveryPlace dp = (DeliveryPlace) obj;
            if (dp.getDeliveryPlaceID() == 0) {
                ValidationUtils.rejectIfEmptyOrWhitespace(err, "street", "field.required");
                ValidationUtils.rejectIfEmptyOrWhitespace(err, "city", "field.required");
                ValidationUtils.rejectIfEmptyOrWhitespace(err, "zip", "field.required");
                if (dp.getStreetNo() == 0) {
                    err.rejectValue("streetNo", "field.id_out_of_bounds");
                }
            } else {
                DeliveryPlaceService dps = new DeliveryPlaceService();
                if (dps != null && dp.getDeliveryPlaceID() < 0 && dp.getDeliveryPlaceID() > dps.getMaxDeliveryPlaceID())
                    err.rejectValue("productID", "field.id_out_of_bounds");
            }
        }
    }
}
